from flask import Flask, request, jsonify
import time
from selenium.webdriver.common.by import By
from seleniumwire import webdriver
import json

app = Flask(__name__)


@app.route('/getXtoken', methods=['GET'])
def getXtoken():

    print("捕获到请求")
    # Extract the query parameters from the request URL
    username = request.args.get('userName')
    password = request.args.get('pwd')

    # Perform any necessary processing or authentication logic here

    firefox_options = webdriver.FirefoxOptions()

    firefox_options.add_argument('--headless')
    firefox_options.add_argument('--no-sandbox')
    firefox_options.add_argument('--disable-dev-shm-usage')
    driver = webdriver.Firefox(options=firefox_options)
    # 创建Firefox
    print("创建Firefox")
    driver.delete_all_cookies()
    firstUrl = 'https://authserver.sandau.edu.cn/authserver/login?service=https%3A%2F%2Fcas.sandau.edu.cn%2Fcas%2Flogin%3Fservice%3Dhttps%253A%252F%252Fsuperapp.sandau.edu.cn%252Fpages%252Ftab%252Findex%252Findex'

    # 打开网页
    driver.get(firstUrl)
    print("打开网页")
    # 输入用户名称
    username_field = driver.find_element(By.ID, "username")
    username_field.send_keys(username)
    # 输入密码
    password_field = driver.find_element(By.ID, "password")
    password_field.send_keys(password)

    driver.find_element(By.ID, "login_submit").click()
    time.sleep(5)
    # 点击更多
    driver.find_elements(By.CLASS_NAME, "item")[-1].click()
    time.sleep(5)
    # 点二课活动
    driver.find_element(By.ID, "mod-ser-index-6").find_elements(By.CLASS_NAME, "item")[-1].click()
    # 这个是通过索引，这个是模糊查找，学到啦！！！ # 点二课活动
    # driver.find_elements(By.XPATH, '//uni-view[contains(text(),"二课-活动中心")]')[-1].click()
    time.sleep(5)

    # 获取X-Id-Token和user_id
    x_id_token = None
    user_id = None

    for seleniumRequest in driver.requests:
        if 'https://stuworkapp.sandau.edu.cn/api/newcapec-common/v1/api/app/privilege/getMyUserInfo' in seleniumRequest.url:
            user_info = json.loads(seleniumRequest.response.body.decode('utf-8'))
            print(user_info)
            user_id = user_info['data']['userId']
            nickName = user_info['data']['nickName']
            x_id_token = seleniumRequest.headers.get("X-Id-Token")
        # Create a JSON response dictionary

    # 关闭浏览器
    driver.quit()
    response = {
        'state': 200,
        'x_id_token': x_id_token,
        'user_id': user_id,
        'nickName': nickName
    }
    # Return the JSON response
    return jsonify(response)


if __name__ == '__main__':
    app.run(host="0.0.0.0",port=8899)
